package edu.spec.teacher.service.impl;

import edu.spec.basic.dao.iface.IUserDao;
import edu.spec.teacher.dao.iface.IElectDao;
import edu.spec.teacher.dao.iface.IUserElectDao;
import edu.spec.teacher.model.Elect;
import edu.spec.teacher.model.UserElect;
import edu.spec.teacher.service.iface.IUserElectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Author       : MadFrog
 * Date         : 2018/10/15 11:14
 * Description  :
 */
@Service
public class UserElectService implements IUserElectService {

    @Autowired
    private IUserElectDao userElectDao;
    @Autowired
    private IElectDao electDao;
    @Autowired
    private IUserDao userDao;

    @Override
    public List<UserElect> listEffectiveByUser(Integer userId) {
        return userElectDao.listEffectiveByUser(userId);
    }

    @Override
    public UserElect load(Integer id){
        return userElectDao.load(id);
    }

    @Override
    public void update(UserElect userElect) {
        userElectDao.update(userElect);

        Elect elect = userElect.getElect();
        // 更新完成数量
        elect.setCompleteNumber(elect.getCompleteNumber() + 1);
        String ratio = elect.getCompleteRatio();
        String[] ratios = ratio.split("/");
        elect.setCompleteRatio(elect.getCompleteNumber() + "/" + ratios[1]);
        // 更新fact
        // 用户的投票
        String votes = userElect.getResult();
        String[] voteArray =  votes.split(",");
        // 汇总记录
        String fact = elect.getFact();
        String[] factArray = fact.split(",");

        for(String vote : voteArray){
            for (int i=0; i<factArray.length; i++){
                String candidate = factArray[i];
                String candidateId = candidate.split(":")[0];
                String candidateName = candidate.split(":")[1];
                String candidateCount = candidate.split(":")[2];
                if (candidateId.equals(vote.split(":")[0])){
                    factArray[i] = candidateId + ":" + candidateName + ":" + (Integer.parseInt(candidateCount) + 1);
                }
            }
        }
        fact = "";
        for (String couple : factArray){
            fact += couple +",";
        }
        fact = fact.substring(0, fact.length()-1);
        elect.setFact(fact);
        electDao.update(elect);
    }

}
